import React from 'react';
import RouterContext from '../RouterContext';
import LifeCycle from './LifeCycle';

export default function Prompt({ message, when }) {
  return (
    <RouterContext.Consumer>
      {(context) => {
        if (!when) return null;

        const method = context.history.block;
        return (
          <LifeCycle
            onMount={(self) => {
              self.release = method((tx) => {
                if (window.confirm(message)) {
                  // block 方法版本升级了，之前是需要自己取消注册事件，现在可以在用户点确定的时候取消注册事件
                  self.release();
                  tx.retry();
                }
              });
            }}
            onUnmount={(self) => {
              self.release();
            }}
          />
        );
      }}
    </RouterContext.Consumer>
  );
}
